package org.jeecg.modules.demo.membermanagement.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.basemembervip.entity.BaseMemberVip;
import org.jeecg.modules.demo.basemembervip.service.IBaseMemberVipService;
import org.jeecg.modules.demo.basemembervipcoupon.entity.BaseMemberVipCoupon;
import org.jeecg.modules.demo.basemembervipcoupon.service.IBaseMemberVipCouponService;
import org.jeecg.modules.demo.baseordercommoditywriteoff.entity.BaseOrderCommodityWriteoff;
import org.jeecg.modules.demo.baseordercommoditywriteoff.service.IBaseOrderCommodityWriteoffService;
import org.jeecg.modules.demo.baseorderproject.entity.BaseOrderProject;
import org.jeecg.modules.demo.baseorderproject.service.IBaseOrderProjectService;
import org.jeecg.modules.demo.baseorderservicewriteoff.entity.BaseOrderServiceWriteoff;
import org.jeecg.modules.demo.baseorderservicewriteoff.service.IBaseOrderServiceWriteoffService;
import org.jeecg.modules.demo.baseorderwriteoffrecord.entity.BaseOrderWriteoffRecord;
import org.jeecg.modules.demo.baseorderwriteoffrecord.service.IBaseOrderWriteoffRecordService;
import org.jeecg.modules.demo.levelset.entity.LevelSet;
import org.jeecg.modules.demo.levelset.service.ILevelSetService;
import org.jeecg.modules.demo.membermanagement.entity.MemberInfo;
import org.jeecg.modules.demo.membermanagement.entity.MemberManagement;
import org.jeecg.modules.demo.membermanagement.entity.MemberManagementVo;
import org.jeecg.modules.demo.membermanagement.entity.MyMemberInfo;
import org.jeecg.modules.demo.membermanagement.service.IMemberManagementService;
import org.jeecg.modules.demo.membertag.entity.MemberTag;
import org.jeecg.modules.demo.membertag.service.IMemberTagService;
import org.jeecg.modules.demo.msgtemplatelist.entity.MsgTemplate;
import org.jeecg.modules.demo.msgtemplatelist.service.IMsgTemplateService;
import org.jeecg.modules.demo.projectmanagement.entity.ProjectManagement;
import org.jeecg.modules.demo.projectmanagement.service.IProjectManagementService;
import org.jeecg.modules.demo.staffmanagement.entity.ServiceDetail;
import org.jeecg.modules.demo.stockmanage.entity.StockManage;
import org.jeecg.modules.demo.stockmanage.service.IStockManageService;
import org.jeecg.modules.demo.storeinfo.entity.StoreInfo;
import org.jeecg.modules.demo.storeinfo.service.IStoreInfoService;
import org.jeecg.modules.demo.tag.entity.Tag;
import org.jeecg.modules.demo.tag.service.ITagService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.util.*;
import org.jeecg.modules.weixin.util;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Api(tags = {"会员管理"})
@RestController
@RequestMapping({"/membermanagement/memberManagement"})
public class MemberManagementController extends JeecgController<MemberManagement, IMemberManagementService> {
    private static final Logger log = LoggerFactory.getLogger(MemberManagementController.class);

    @Autowired
    private IMemberManagementService memberManagementService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IStoreInfoService storeInfoService;

    @Autowired
    private IStockManageService stockManageService;

    @Autowired
    private ILevelSetService levelSetService;

    @Autowired
    private IBaseMemberVipService baseMemberVipService;

    @Autowired
    private IBaseMemberVipCouponService baseMemberVipCouponService;

    @Autowired
    private IBaseOrderProjectService baseOrderProjectService;

    @Autowired
    private IBaseOrderServiceWriteoffService baseOrderServiceWriteoffService;

    @Autowired
    private IBaseOrderCommodityWriteoffService baseOrderCommodityWriteoffService;

    @Autowired
    private IBaseOrderWriteoffRecordService baseOrderWriteoffRecordService;

    @Autowired
    private IMemberTagService memberTagService;

    @Autowired
    private IProjectManagementService projectManagementService;

    @Autowired
    private ITagService tagService;

    @Autowired
    private IMsgTemplateService msgTemplateListService;

    @Value("${jeecg.path.upload}")
    private String upLoadPath;

    @AutoLog("会员管理-分页列表查询")
    @ApiOperation(value = "会员管理-分页列表查询", notes = "会员管理-分页列表查询")
    @GetMapping({"/pageList"})
    public Result<?> queryPageList(MemberManagement memberManagement,
                                   @RequestParam(name = "tag", defaultValue = "0") String tagId,
                                   @RequestParam(name = "highStockdId", defaultValue = "0") String highStockdId,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) this.redisUtils.get("StoreId-" + token);
        if (oConvertUtils.isEmpty(storeId))
            return Result.error("请先到首页选择店铺");
        if (storeId.contains("过期"))
            return Result.error("店铺已过期，续费后才可操作");
        QueryWrapper<MemberManagement> queryWrapper = new QueryWrapper();
        queryWrapper.eq("store_id", storeId);
       // queryWrapper.eq("userinfo_status", "1");
        if (!highStockdId.equals("0")) {
            queryWrapper.eq("high_stock_id", highStockdId);
        } else {
            QueryGenerator.initQueryWrapper(queryWrapper, memberManagement, req.getParameterMap());
        }
        if (!"0".equals(tagId)){
            queryWrapper.in("id",memberTagService.getMembersIdByTagId(storeId,tagId));
        }

        Page<MemberManagement> page = new Page(pageNo, pageSize);
        IPage<MemberManagement> pageList = this.memberManagementService.page((IPage) page, queryWrapper);

        List<MemberManagement> records = pageList.getRecords();
        records.forEach(mm -> {
            StoreInfo store = this.storeInfoService.getById(mm.getStoreId());
            if (store != null)
                mm.setBelongStore(store.getStoreName());
            StockManage stock = this.stockManageService.getById(mm.getStockId());
            if (stock != null)
                mm.setShareholders(stock.getStockName() + stock.getTel());
            LevelSet level = this.levelSetService.getById(mm.getLevelId());
            if (level != null)
                mm.setMemberLevel(level.getRankName());
            Integer relationAllQty = this.memberManagementService.getRelationsAllQty(mm.getId(), storeId);
            this.memberManagementService.updateRelationQty(mm.getId(), relationAllQty);
        });
        Map<String, Object> map = BeanUtils.bean2Map(pageList);
        List<Map<String, Object>> list = new ArrayList<>();
        for (MemberManagement m : records) {
            Map<String, Object> map1 = BeanUtils.bean2Map(m);

            List<MemberTag> taglist = this.memberTagService.list((Wrapper) ((QueryWrapper) (new QueryWrapper()).eq("store_id", m.getStoreId())).eq("member_id", m.getId()));
            List<String> sl = new ArrayList<>();
            for (MemberTag tag : taglist) {
                if (!StringUtils.isEmpty(tag.getTagId())) {
                    Tag vt = this.tagService.getById(tag.getTagId());
                    if (vt != null)
                        sl.add(vt.getName());
                }
            }
            map1.put("tags", ListUtils.list2Str(sl));

            list.add(map1);
        }
        map.put("records", list);
        return Result.OK(map);
    }

    @AutoLog("会员管理-列出标签")
    @ApiOperation(value = "会员管理-列出标签", notes = "会员管理-列出标签（？）")
    @GetMapping({"/listTags"})
    public Result<?> listTags(HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) this.redisUtils.get("StoreId-" + token);
        if (oConvertUtils.isEmpty(storeId))
            return Result.error("请先到首页选择店铺");
        if (storeId.contains("过期"))
            return Result.error("店铺已过期，续费后才可操作");
        List<Tag> list = this.tagService.list((Wrapper) (new QueryWrapper()).eq("store_id", storeId));
        List<Map<String, String>> r = new ArrayList<>();
        for (Tag tag : list) {
            Map<String, String> m = new HashMap<>();
            m.put("id", tag.getId());
            m.put("name", tag.getName());
            r.add(m);
        }
        return Result.ok(list);
    }

    @AutoLog("会员管理-列出标签")
    @ApiOperation(value = "会员管理-列出标签", notes = "会员管理-列出标签（？）")
    @GetMapping({"/listMemberByTag"})
    public Result<?> listMemberByTag(@RequestParam(name = "tagId", required = true) String tagId, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) this.redisUtils.get("StoreId-" + token);
        if (oConvertUtils.isEmpty(storeId))
            return Result.error("请先到首页选择店铺");
        if (storeId.contains("过期"))
            return Result.error("店铺已过期，续费后才可操作");
        List<MemberManagement> list = this.memberTagService.getMembersByTagId(storeId, tagId);
        return Result.ok(list);
    }

    @AutoLog("会员管理-根据id查询会员信息")
    @ApiOperation(value = "会员管理-根据id查询会员信息", notes = "会员管理-根据id查询会员信息（？）")
    @GetMapping({"/getMemberinfoById"})
    public Result<MemberInfo> getMemberinfoById(@RequestParam(name = "storeId", required = true) String storeId, @RequestParam(name = "memberId", required = true) String memberId) {
        Result<MemberInfo> result = new Result();
        MemberInfo memberInfo = this.memberManagementService.getMemberinfoById(storeId, memberId);
        result.setSuccess(true);
        result.setResult(memberInfo);
        return result;
    }

    @AutoLog("会员管理-分页列表查询")
    @ApiOperation(value = "会员管理-分页列表查询", notes = "会员管理-分页列表查询（？）")
    @GetMapping({"/queryList"})
    public Result<?> queryList(MemberManagement memberManagement, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) this.redisUtils.get("StoreId-" + token);
        if (oConvertUtils.isEmpty(storeId))
            return Result.error("请先到首页选择店铺");
        if (storeId.contains("过期"))
            return Result.error("店铺已过期，续费后才可操作");
        QueryWrapper<MemberManagement> queryWrapper = QueryGenerator.initQueryWrapper(memberManagement, req.getParameterMap());
        queryWrapper.eq("store_id", storeId);
        List<MemberManagement> pageList = this.memberManagementService.list(queryWrapper);
        return Result.OK(pageList);
    }

    @AutoLog("会员管理-查询非股东会员")
    @ApiOperation(value = "会员管理-查询非股东会员", notes = "会员管理-查询非股东会员")
    @GetMapping({"/getNotStockMember"})
    public Result<?> getNotStockMember(HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) this.redisUtils.get("StoreId-" + token);
        if (oConvertUtils.isEmpty(storeId))
            return Result.error("请先到首页选择店铺");
        if (storeId.contains("过期"))
            return Result.error("店铺已过期，续费后才可操作");
        List<MemberManagement> pageList = this.memberManagementService.getNotStockMember(storeId);
        return Result.OK(pageList);
    }

    @AutoLog("会员管理-姓名电话列表")
    @ApiOperation(value = "会员管理-姓名电话列表", notes = "会员管理-姓名电话列表（？）")
    @GetMapping({"/listForName"})
    public Result<?> listForName(@RequestParam(name = "tagId", required = true, defaultValue = "0") String tagId, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) this.redisUtils.get("StoreId-" + token);
        if (oConvertUtils.isEmpty(storeId))
            return Result.error("请先到首页选择店铺");
        if (storeId.contains("过期"))
            return Result.error("店铺已过期，续费后才可操作");
        if ("0".equals(tagId)) {
            QueryWrapper<MemberManagement> queryWrapper = new QueryWrapper();
            queryWrapper.in("store_id", storeId);
            queryWrapper.eq("userinfo_status", "1");
            List<MemberManagement> listData = this.memberManagementService.list(queryWrapper);
            List<Map<String, String>> list1 = new ArrayList<>();
            for (MemberManagement bean : listData) {
                Map<String, String> map = new HashMap<>();
                map.put("id", bean.getId());
                map.put("value", bean.getName() + "-" + bean.getPhone());
                list1.add(map);
            }
            return Result.OK(list1);
        }
        List<MemberManagement> list = this.memberTagService.getMembersByTagId(storeId, tagId);
        List<Map<String, String>> newListData = new ArrayList<>();
        for (MemberManagement bean : list) {
            Map<String, String> map = new HashMap<>();
            map.put("id", bean.getId());
            map.put("value", bean.getName() + "-" + bean.getPhone());
            newListData.add(map);
        }
        return Result.OK(newListData);
    }

    @RequestMapping(value = {"/getMyMemberList"}, method = {RequestMethod.GET})
    public Result<List<MyMemberInfo>> getMyMemberList(@RequestParam(name = "pageNo", required = true) Integer pageNo, @RequestParam(name = "storeId", required = true) String storeId, @RequestParam(name = "memberId", required = true) String memberId) {
        Result<List<MyMemberInfo>> result = new Result();
        List<MyMemberInfo> list = this.memberManagementService.getMyMemberList(pageNo, Integer.valueOf(10), storeId, memberId);
        result.setSuccess(true);
        result.setResult(list);
        return result;
    }

    @PostMapping({"/listMemberProject"})
    public Result<?> listMemberProject(@RequestBody Map<String, Object> map, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) this.redisUtils.get("StoreId-" + token);
        if (oConvertUtils.isEmpty(storeId))
            return Result.error("请先到首页选择店铺");
        if (storeId.contains("过期"))
            return Result.error("店铺已过期，续费后才可操作");
        map.put("storeId", storeId);
        String memberId = (map.get("memberId") == null) ? null : String.valueOf(map.get("memberId"));
        if (StringUtils.isEmpty(memberId))
            return Result.error("参数不全");
        List<Map<String, Object>> maps = this.memberManagementService.listMemberProject(map);

        for (Map<String, Object> vMap : maps) {
            if (vMap==null){
                continue;
            }
            String content = vMap.get("content")==null?null:vMap.get("content").toString();

            Object o = vMap.get("validateTime");
            if (content == null || o == null) {
                continue;
            }
            if (o instanceof Date) {
                Date date = (Date) o;
                String cardName = TimeCardUtils.getCardName(content, date);
                vMap.put("content", cardName);
            }
        }
        return Result.OK(maps);
    }

    @PostMapping({"/listMemberProjectShopAndServe"})
    public Result<?> listMemberProjectShopAndServe(@RequestBody Map<String, Object> map, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) this.redisUtils.get("StoreId-" + token);
        if (oConvertUtils.isEmpty(storeId))
            return Result.error("请先到首页选择店铺");
        if (storeId.contains("过期"))
            return Result.error("店铺已过期，续费后才可操作");
        map.put("storeId", storeId);
        String orderProjectId = (map.get("orderProjectId") == null) ? null : String.valueOf(map.get("orderProjectId"));
        if (StringUtils.isEmpty(orderProjectId))
            return Result.error("参数不全");
        List<BaseOrderServiceWriteoff> serveList = this.baseOrderServiceWriteoffService.list((Wrapper) (new QueryWrapper())
                .eq("order_project_id", orderProjectId));
        String leftDays = "";
        BaseOrderProject orderProject = this.baseOrderProjectService.getById(orderProjectId);
        if (orderProject != null && orderProject.getValidateTime() == null) {
            ProjectManagement project = this.projectManagementService.getById(orderProject.getProjectId());
            orderProject.setIndate(project.getIndate());
            orderProject.setTimingWay(project.getTimingWay());
            if (project.getTimingWay().equals("1")) {
                Date createTime = orderProject.getCreateTime();
                Date date = new Date(createTime.getTime() + 86400000L * Integer.valueOf(project.getIndate()).intValue());
                orderProject.setValidateTime(date);
            } else if (serveList.size() > 0) {
                Date createTime = getEalistDate(serveList);
                Date date = new Date(createTime.getTime() + 86400000L * Integer.valueOf(project.getIndate()).intValue());
                orderProject.setValidateTime(date);
                int differDays = DateUtils.getDifferDays(date, new Date());
                leftDays = Math.abs(differDays) + "天";
            }
        }
        List<BaseOrderCommodityWriteoff> commodityList1 = this.baseOrderCommodityWriteoffService.list((Wrapper) (new QueryWrapper())
                .eq("order_project_id", orderProjectId));
        List<Object> commodityList = commodityList1.stream().map(o -> {
            Map<String, Object> m = ToolsUtils.objectToMap(o);
            m.put("type", "1");
            return m;
        }).collect(Collectors.toList());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        List<BaseOrderWriteoffRecord> writeoffRecordList = this.baseOrderWriteoffRecordService.list((Wrapper) (new QueryWrapper())
                .eq("order_project_id", orderProjectId));
        for (BaseOrderWriteoffRecord record : writeoffRecordList) {
            JSONArray cList = JSONArray.parseArray(record.getCommodityListJsonStr());
            for (int i = 0; i < cList.size(); i++) {
                JSONObject jsonObject = cList.getJSONObject(i);
                jsonObject.put("type", "2");
                jsonObject.put("writeoffTime", sdf.format(jsonObject.getDate("writeoffTime")));
                commodityList.add(cList.getJSONObject(i));
            }
        }
        Map<String, Object> result = new HashMap<>();
        result.put("commodityList", commodityList);
        result.put("serveList", serveList);
        result.put("totalDays", orderProject.getIndate() + "天");
        result.put("leftDays", leftDays);
        return Result.OK(result);
    }

    private Date getEalistDate(List<BaseOrderServiceWriteoff> serveList) {
        Date result = new Date();
        for (BaseOrderServiceWriteoff r : serveList) {
            if (result.getTime() > r.getCreateTime().getTime())
                result = r.getCreateTime();
        }
        return result;
    }

    @GetMapping({"/getVipList"})
    public Result<?> getVipList(@RequestParam(value = "cardId", required = false) String cardId, @RequestParam("memberId") String memberId, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) this.redisUtils.get("StoreId-" + token);
        if (oConvertUtils.isEmpty(storeId))
            return Result.error("请先到首页选择店铺");
        if (storeId.contains("过期"))
            return Result.error("店铺已过期，续费后才可操作");
        List<BaseMemberVip> list = this.baseMemberVipService.list(((QueryWrapper) ((QueryWrapper) (new QueryWrapper())
                .eq("store_id", storeId))
                .eq("member_id", memberId))
                .like(StringUtils.isNotEmpty(cardId), "card_id", cardId));
        return Result.OK(list);
    }

    @GetMapping({"/getCouponListByVip"})
    public Result<?> getVipList(@RequestParam("vipId") String vipId, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) this.redisUtils.get("StoreId-" + token);
        if (oConvertUtils.isEmpty(storeId))
            return Result.error("请先到首页选择店铺");
        if (storeId.contains("过期"))
            return Result.error("店铺已过期，续费后才可操作");
        List<BaseMemberVipCoupon> list = this.baseMemberVipCouponService.list((Wrapper) (new QueryWrapper()).eq("member_vip_id", vipId));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
        List<Map<String, Object>> result = list.stream().filter(bmvc -> (bmvc.getNum().intValue() > 0)).map(bmvc -> {
            Map<String, Object> m = ToolsUtils.objectToMap(bmvc);
            m.put("isCouponOutTime", Boolean.valueOf(isCouponOutTime(bmvc)));
            Date fullDate = (Date) m.get("fullDate");
            if (fullDate != null)
                m.put("fullDate", sdf2.format(fullDate));
            Date fullNextDate = (Date) m.get("fullNextDate");
            if (fullNextDate != null)
                m.put("fullNextDate", sdf2.format(fullNextDate));
            Date createTime = (Date) m.get("createTime");
            if (createTime != null)
                m.put("createTime", sdf.format(createTime));
            Date updateTime = (Date) m.get("updateTime");
            if (updateTime != null)
                m.put("updateTime", sdf.format(updateTime));
            return m;
        }).collect(Collectors.toList());
        return Result.OK(result);
    }

    private boolean isCouponOutTime(BaseMemberVipCoupon bmvc) {
        if ("0".equals(bmvc.getFullSelect())) {
            Date endDate = bmvc.getFullNextDate();
            Date now = new Date();
            return now.after(endDate);
        }
        if ("1".equals(bmvc.getFullSelect())) {
            Date createTime = bmvc.getCreateTime();
            Integer day = Integer.valueOf(bmvc.getManualDateNum());
            Calendar c = Calendar.getInstance();
            c.setTime(createTime);
            c.add(5, day.intValue());
            Date endDate = c.getTime();
            Date now = new Date();
            return now.after(endDate);
        }
        return false;
    }

    @GetMapping({"/getRelationsAll"})
    public Result<?> getRelationsAll(@RequestParam(value = "id", required = true) String id, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) this.redisUtils.get("StoreId-" + token);
        if (oConvertUtils.isEmpty(storeId))
            return Result.error("请先到首页选择店铺");
        if (storeId.contains("过期"))
            return Result.error("店铺已过期，续费后才可操作");
        List<MemberManagement> list = this.memberManagementService.getRelationsAll(id, storeId);
        return Result.OK(list);
    }

    @AutoLog("会员管理-添加")
    @ApiOperation(value = "会员管理-添加", notes = "会员管理-添加")
    @PostMapping({"/add"})
    @Transactional(rollbackFor = {JeecgBootException.class})
    public Result<?> add(@RequestBody MemberManagementVo memberManagementVo, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) this.redisUtils.get("StoreId-" + token);
        if (oConvertUtils.isEmpty(storeId))
            return Result.error("请先到首页选择店铺");
        if (storeId.contains("过期"))
            return Result.error("店铺已过期，续费后才可操作");
        MemberManagement memberManagement = new MemberManagement();
        org.springframework.beans.BeanUtils.copyProperties(memberManagementVo, memberManagement);
        int count = this.memberManagementService.count((Wrapper) ((QueryWrapper) (new QueryWrapper())
                .eq("store_id", storeId))
                .eq("phone", memberManagement.getPhone()));
        if (count > 0)
            return Result.error("手机号已存在");
        memberManagement.setStoreId(storeId);
        memberManagement.setConsumption(Integer.valueOf(0));
        memberManagement.setAmount(Double.valueOf(0.0D));
        memberManagement.setBalance(Double.valueOf(0.0D));
        memberManagement.setExpendamount(Double.valueOf(0.0D));
        memberManagement.setShareholderDividends(Double.valueOf(0.0D));
        memberManagement.setStockMemberExpendamount(Double.valueOf(0.0D));
        memberManagement.setRegistrationDate(new Date());
        memberManagement.setWhetherConcern("0");
        memberManagement.setIsNew("0");
        if ("股东会员".equals(memberManagement.getMemberType())) {
            if (StringUtils.isEmpty(memberManagement.getStockId()))
                return Result.error("股东会员必须关联股东");
            memberManagement.setStatus("1");
            memberManagement.setMemberType("股东会员");
            memberManagement.setStockMemberTime(new Date());
            try {
                StockManage stock = this.stockManageService.getById(memberManagement.getStockId());
                MemberManagement stockMember = this.memberManagementService.getById(stock.getMemberId());
                memberManagement.setHighStockId(stockMember.getStockId());
                String gzhOpenId = stockMember.getGzhOpenId();
                String bossGzhOpenId = this.storeInfoService.getBossGzhOpenId(storeId);
                if (gzhOpenId == null) {
                    log.info("发送成为股东会员模板推送失败，股东未绑定公众号");
                } else {
                    StoreInfo store = this.storeInfoService.getById(storeId);
                    if (store == null) {
                        log.info("发送成为股东会员模板推送失败，未查到店铺信息");
                    } else {
                        String gzhAppId = store.getGzhAppId();
                        String gzhAppSecret = store.getGzhAppSecret();
                        if (StringUtils.isEmpty(gzhAppId) || StringUtils.isEmpty(gzhAppSecret)) {
                            log.info("发送成为股东会员模板推送失败，店铺未绑定公众号");
                        } else {
                            String url1 = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + gzhAppId + "&secret=" + gzhAppSecret;
                            String result1 = HttpUtils.sendGet(url1);
                            JSONObject resultJson1 = JSON.parseObject(result1);
                            String errcode = resultJson1.getString("errcode");
                            if (errcode != null && !"0".equals(errcode)) {
                                log.info("发送成为股东会员模板推送失败，获取accessToken返回值异常，错误码：{}", errcode);
                            } else {
                                String accessToken = resultJson1.getString("access_token");
                                String memberPhone = memberManagement.getPhone();
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月d日 HH:mm");
                                MsgTemplate msgTemplate = this.msgTemplateListService.getByTitle("推荐会员成功提醒", storeId);
                                String templateId = msgTemplate.getTemplateId();
                                util.recommendMemberSuccessNotice(templateId, gzhOpenId, memberPhone.substring(0, 3) + "****" + memberPhone.substring(7), sdf.format(new Date()), store.getXcxAppId(), "user/share/tourist", accessToken);
                                log.info("发送成为股东会员模板推送成功");
                            }
                        }
                    }
                }
            } catch (Exception e) {
                log.error("发送成为股东会员模板推送失败，发生异常", e);
            }
        } else {
            memberManagement.setStatus("2");
            memberManagement.setMemberType("店铺会员");
        }
        if (StringUtils.isEmpty(memberManagement.getLevelId())) {
            List<LevelSet> levelSetList = this.levelSetService.list((Wrapper) ((QueryWrapper) (new QueryWrapper()).eq("store_id", storeId)).orderByAsc("rank_num"));
            if (levelSetList == null || levelSetList.size() == 0)
                return Result.error("未选择会员等级，且店铺还未创建会员等级");
            memberManagement.setLevelId(levelSetList.get(0).getId());
        }
        memberManagement.setShareholders(null);
        memberManagement.setBelongStore(null);
        memberManagement.setMemberLevel(null);
        memberManagement.setUserinfoStatus("1");
        this.memberManagementService.save(memberManagement);
        String memberId = memberManagement.getId();
        String tags = memberManagementVo.getTags();
        deal(storeId, memberId, tags);
        return Result.OK("添加成功！");
    }

    @Transactional
    protected void deal(String storeId, String memberId, String tags) {
        String[] sTags = new String[0];
        if (!StringUtils.isEmpty(tags))
            sTags = tags.split(",");
        QueryWrapper<MemberTag> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("store_id", storeId);
        queryWrapper2.eq("member_id", memberId);

        memberTagService.remove(queryWrapper2);

        for (String  name : sTags) {
            QueryWrapper<Tag> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("store_id", storeId);
            queryWrapper.eq("name", name);

            Tag tag = this.tagService.getOne(queryWrapper);
            if (tag!=null){//

            }else{
                 tag = new Tag();
                tag.setName(name);
                tag.setStoreId(storeId);
                this.tagService.save(tag);
            }

            MemberTag memberTag = new MemberTag();
            memberTag.setMemberId(memberId);
            memberTag.setTagId(tag.getId());
            memberTag.setStoreId(storeId);
            this.memberTagService.save(memberTag);
        }


/*
        List<String> nameList = new ArrayList<>();
        Collections.singletonList(nameList);

        List<Tag> tagList = this.tagService.list((Wrapper) (new QueryWrapper()).eq("store_id", storeId));

        List<String> tagNameList = new ArrayList<>();
        List<String> nameCreatedList = new ArrayList<>();
        List<String> nameToCreateList = new ArrayList<>();

        List<String> tagIdList = new ArrayList<>();

        for (Tag tag : tagList) {
            tagNameList.add(tag.getName());
            if (nameList.contains(tag.getName()))
                tagIdList.add(tag.getId());
        }
        for (String vTag : sTags) {
            if (tagNameList.contains(vTag)) {
                nameCreatedList.add(vTag);
            } else {
                nameToCreateList.add(vTag);
            }
        }

        for (String vTag : nameToCreateList) {
            Tag tag = new Tag();
            tag.setName(vTag);
            tag.setStoreId(storeId);
            this.tagService.save(tag);

            if (!StringUtils.isBlank(memberId)) {
                MemberTag memberTag = new MemberTag();
                memberTag.setMemberId(memberId);
                memberTag.setTagId(tag.getId());
                memberTag.setStoreId(storeId);
                this.memberTagService.save(memberTag);
            }
        }
        List<MemberTag> list = new ArrayList<>();
        for (String tagId : tagIdList) {
            MemberTag memberTag = new MemberTag();
            memberTag.setStoreId(storeId);
            memberTag.setMemberId(memberId);
            memberTag.setTagId(tagId);
            list.add(memberTag);
        }
        this.memberTagService.saveBatch(list);*/
    }

    @AutoLog("会员管理-编辑")
    @ApiOperation(value = "会员管理-编辑", notes = "会员管理-编辑")
    @PutMapping({"/edit"})
    @Transactional(rollbackFor = {Exception.class})
    public Result<?> edit(@RequestBody MemberManagementVo memberManagementVo, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) this.redisUtils.get("StoreId-" + token);
        if (oConvertUtils.isEmpty(storeId))
            return Result.error("请先到首页选择店铺");
        if (storeId.contains("过期"))
            return Result.error("店铺已过期，续费后才可操作");
        MemberManagement memberManagement = new MemberManagement();
        org.springframework.beans.BeanUtils.copyProperties(memberManagementVo, memberManagement);
        int count = this.memberManagementService.count((Wrapper) ((QueryWrapper) ((QueryWrapper) (new QueryWrapper())
                .eq("store_id", storeId))
                .eq("phone", memberManagement.getPhone()))
                .ne("id", memberManagement.getId()));
        if (count > 0)
            return Result.error("手机号已存在");
        MemberManagement old = this.memberManagementService.getById(memberManagement.getId());
        if (!StringUtils.equals(old.getLevelId(), memberManagement.getLevelId()))
            try {
                String gzhOpenId = old.getGzhOpenId();
                String bossGzhOpenId = this.storeInfoService.getBossGzhOpenId(storeId);
                if (gzhOpenId == null) {
                    log.info("发送会员等级变更模板推送失败，会员未绑定公众号");
                } else {
                    StoreInfo store = this.storeInfoService.getById(storeId);
                    if (store == null) {
                        log.info("发送会员等级变更模板推送失败，未查到店铺信息");
                    } else {
                        String gzhAppId = store.getGzhAppId();
                        String gzhAppSecret = store.getGzhAppSecret();
                        if (StringUtils.isEmpty(gzhAppId) || StringUtils.isEmpty(gzhAppSecret)) {
                            log.info("发送会员等级变更模板推送失败，店铺未绑定公众号");
                        } else {
                            String url1 = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + gzhAppId + "&secret=" + gzhAppSecret;
                            String result1 = HttpUtils.sendGet(url1);
                            JSONObject resultJson1 = JSON.parseObject(result1);
                            String errcode = resultJson1.getString("errcode");
                            if (errcode != null && !"0".equals(errcode)) {
                                log.info("发送会员等级变更模板推送失败，获取accessToken返回值异常，错误码：{}", errcode);
                            } else {
                                String accessToken = resultJson1.getString("access_token");
                                LevelSet oldLevel = this.levelSetService.getById(old.getLevelId());
                                LevelSet newLevel = this.levelSetService.getById(memberManagement.getLevelId());
                                if (oldLevel == null || newLevel == null) {
                                    log.info("发送会员等级变更模板推送失败，会员等级名称获取失败");
                                } else {
                                    MsgTemplate msgTemplate = this.msgTemplateListService.getByTitle("会员等级变更通知", storeId);
                                    String templateId = msgTemplate.getTemplateId();
                                    util.levelChangeNotice(templateId, gzhOpenId, oldLevel.getRankName(), newLevel.getRankName(), String.valueOf(newLevel.getDiscount()), store.getXcxAppId(), "pages/index/index", accessToken);
                                    log.info("发送会员等级变更模板推送成功");
                                }
                            }
                        }
                    }
                }
            } catch (Exception e) {
                log.error("发送会员等级变更模板推送成功，发生异常", e);
            }
        if ("股东会员".equals(memberManagement.getMemberType())) {
            if (StringUtils.isEmpty(memberManagement.getStockId()))
                return Result.error("股东会员必须关联股东");
            StockManage stock = this.stockManageService.getById(memberManagement.getStockId());
            if (stock.getMemberId().equals(memberManagement.getId()))
                return Result.error("不能成为自己的股东会员");
            memberManagement.setStatus("1");
            memberManagement.setMemberType("股东会员");
            memberManagement.setStockMemberTime(new Date());
        } else {
            memberManagement.setStatus("2");
            memberManagement.setMemberType("店铺会员");
            memberManagement.setStockMemberExpendamount(Double.valueOf(0.0D));
            memberManagement.setStockId("");
        }
        memberManagement.setShareholders(null);
        memberManagement.setBelongStore(null);
        memberManagement.setMemberLevel(null);
        this.memberManagementService.updateById(memberManagement);
        if (StringUtils.isNotEmpty(memberManagement.getMyStockId())) {
            StockManage myStock = this.stockManageService.getById(memberManagement.getMyStockId());
            myStock.setStockName(memberManagement.getName());
            myStock.setTel(memberManagement.getPhone());
            this.stockManageService.updateById(myStock);
        }
        String memberId = memberManagement.getId();
        String tags = memberManagementVo.getTags();
        deal(storeId, memberId, tags);
        return Result.OK("编辑成功!");
    }

    @AutoLog("会员管理-通过id删除")
    @ApiOperation(value = "会员管理-通过id删除", notes = "会员管理-通过id删除")
    @DeleteMapping({"/delete"})
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        MemberManagement mm = this.memberManagementService.getById(id);
        if (StringUtils.isNotEmpty(mm.getMyStockId()))
            return Result.error("该会员有股东身份，请删除股东身份后再删除会员!");
        this.memberManagementService.removeById(id);
        return Result.OK("删除成功!");
    }

    @AutoLog("会员管理-批量删除")
    @ApiOperation(value = "会员管理-批量删除", notes = "会员管理-批量删除")
    @DeleteMapping({"/deleteBatch"})
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        return Result.error("暂不支持批量删除!");
    }

    @AutoLog("会员管理-通过id查询")
    @ApiOperation(value = "会员管理-通过id查询", notes = "会员管理-通过id查询")
    @GetMapping({"/queryById"})
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        MemberManagement memberManagement = this.memberManagementService.getById(id);
        if (memberManagement == null)
            return Result.error("未找到对应数据");
        return Result.OK(memberManagement);
    }

    @RequestMapping({"/exportXls"})
    public ModelAndView exportXls(HttpServletRequest request, MemberManagement memberManagement) {
        String token = TokenUtils.getTokenByRequest(request);
        String storeId = (String) this.redisUtils.get("StoreId-" + token);
        QueryWrapper<MemberManagement> queryWrapper = new QueryWrapper();
        queryWrapper.eq("store_id", storeId);
        queryWrapper.eq("userinfo_status", "1");
        QueryGenerator.initQueryWrapper(queryWrapper, memberManagement, request.getParameterMap());
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<MemberManagement> pageList = this.memberManagementService.list(queryWrapper);
        pageList.forEach(mm -> {
            StoreInfo store = this.storeInfoService.getById(mm.getStoreId());
            if (store != null)
                mm.setBelongStore(store.getStoreName());
            StockManage stock = this.stockManageService.getById(mm.getStockId());
            if (stock != null)
                mm.setShareholders(stock.getStockName() + stock.getTel());
            LevelSet level = this.levelSetService.getById(mm.getLevelId());
            if (level != null)
                mm.setMemberLevel(level.getRankName());
        });
        mv.addObject("fileName", "会员列表");
        mv.addObject("entity", MemberManagement.class);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        ExportParams exportParams = new ExportParams("会员列表数据", "导出人:" + user.getRealname(), "会员列表");
        exportParams.setImageBasePath(this.upLoadPath);
        mv.addObject("params", exportParams);
        mv.addObject("data", pageList);
        return mv;
    }

    @RequestMapping(value = {"/importExcel"}, method = {RequestMethod.POST})
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return importExcel(request, response, MemberManagement.class);
    }

    @GetMapping({"/getTemplate"})
    @ApiOperation("获取模板")
    public void getTemplate(HttpServletResponse response) throws Exception {
        File file = new File("/usr/local/project/template/会员导入模板.xlsx");
        XSSFWorkbook workbook = new XSSFWorkbook(file);
        String fileName = URLEncoder.encode("会员导入模板", "utf-8") + ".xlsx";
        response.setHeader("contentType", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("content-disposition", "attachment;fileName=" + fileName);
        response.setHeader("FileName", fileName);
        response.setHeader("Access-Control-Expose-Headers", "FileName");
        response.flushBuffer();
        ServletOutputStream servletOutputStream = response.getOutputStream();
        workbook.write(response.getOutputStream());
        workbook.close();
        servletOutputStream.flush();
        servletOutputStream.close();
    }

    @PostMapping({"/import"})
    @ApiOperation("导入")
    public Result<?> importOwnerCert(@RequestParam("file") MultipartFile file, HttpServletRequest req) {
        XSSFSheet sheet;
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) this.redisUtils.get("StoreId-" + token);
        if (oConvertUtils.isEmpty(storeId))
            return Result.error("请先到首页选择店铺");
        if (storeId.contains("过期"))
            return Result.error("店铺已过期，续费后才可操作");
        List<LevelSet> levelSetList = this.levelSetService.list((Wrapper) ((QueryWrapper) (new QueryWrapper()).eq("store_id", storeId)).orderByAsc("rank_num"));
        if (levelSetList == null || levelSetList.size() == 0)
            return Result.error("店铺还未创建会员等级，需要相关人员先创建会员等级");
        String levelId = levelSetList.get(0).getId();
        String filename = file.getOriginalFilename();
        if (filename != null && !filename.endsWith(".xlsx"))
            return Result.error("文件格式不正确");
        try (InputStream is = file.getInputStream()) {
            XSSFWorkbook workbook = new XSSFWorkbook(is);
            sheet = workbook.getSheetAt(0);
        } catch (IOException e) {
            return Result.error("文件读取失败");
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            XSSFRow row = sheet.getRow(i);
            if (row == null) {
                if (i == 1)
                    return Result.error("单元格" + sheet.createRow(i).createCell(0).getAddress().formatAsString() + "无数据");
                if (sb.length() == 0)
                    return Result.OK("导入成功");
                return Result.error(sb.toString());
            }
            String name = getCellStringValue(row.getCell(0));
            if (StringUtils.isEmpty(name)) {
                sb.append("第" + i + "行导入失败：单元格" + row.createCell(0).getAddress().formatAsString() + "姓名不能为空\r\n");
            } else {
                String phone = getCellStringValue(row.getCell(1));
                if (StringUtils.isEmpty(phone)) {
                    sb.append("第" + i + "行导入失败：单元格" + row.createCell(1).getAddress().formatAsString() + "手机号不能为空\r\n");
                } else {
                    String sexStr = getCellStringValue(row.getCell(2));
                    if (sexStr != null && !"男".equals(sexStr) && !"女".equals(sexStr) && !"保密".equals(sexStr)) {
                        sb.append("第" + i + "行导入失败：单元格" + row.createCell(2).getAddress().formatAsString() + "性别数据错误\r\n");
                    } else {
                        String sex = "男".equals(sexStr) ? "01" : ("女".equals(sexStr) ? "02" : ("保密".equals(sexStr) ? "03" : null));
                        int count = this.memberManagementService.count((Wrapper) ((QueryWrapper) (new QueryWrapper())
                                .eq("store_id", storeId))
                                .eq("phone", phone));
                        if (count > 0) {
                            sb.append("第" + i + "行导入失败：单元格" + row.createCell(1).getAddress().formatAsString() + "手机号已存在\r\n");
                        } else {
                            MemberManagement memberManagement = new MemberManagement();
                            memberManagement.setStoreId(storeId);
                            memberManagement.setName(name);
                            memberManagement.setPhone(phone);
                            memberManagement.setSex(sex);
                            memberManagement.setConsumption(Integer.valueOf(0));
                            memberManagement.setAmount(Double.valueOf(0.0D));
                            memberManagement.setBalance(Double.valueOf(0.0D));
                            memberManagement.setExpendamount(Double.valueOf(0.0D));
                            memberManagement.setShareholderDividends(Double.valueOf(0.0D));
                            memberManagement.setStockMemberExpendamount(Double.valueOf(0.0D));
                            memberManagement.setRegistrationDate(new Date());
                            memberManagement.setWhetherConcern("0");
                            memberManagement.setStatus("2");
                            memberManagement.setMemberType("店铺会员");
                            memberManagement.setLevelId(levelId);
                            memberManagement.setIsNew("0");
                            memberManagement.setUserinfoStatus("1");
                            this.memberManagementService.save(memberManagement);
                        }
                    }
                }
            }
        }
        if (sb.length() == 0)
            return Result.OK("导入成功");
        return Result.error(sb.toString());
    }

    private String getCellStringValue(Cell cell) {
        return isEmptyCell(cell) ? null : String.valueOf(cell).trim();
    }

    private boolean isEmptyCell(Cell cell) {
        return (cell == null || StringUtils.isEmpty(String.valueOf(cell).trim()));
    }

    @AutoLog("会员管理-查询所有标签")
    @ApiOperation(value = "0515会员管理-查询所有标签", notes = "会员管理-查询所有标签")
    @GetMapping({"/listTag"})
    public Result<?> listTag(HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) this.redisUtils.get("StoreId-" + token);
        if (oConvertUtils.isEmpty(storeId))
            return Result.error("请先到首页选择店铺");
        if (storeId.contains("过期"))
            return Result.error("店铺已过期，续费后才可操作");
        List<Tag> tags = this.tagService.list((Wrapper) (new QueryWrapper()).eq("store_id", storeId));
        return Result.OK(tags);
    }

    @AutoLog("会员管理-查询标签")
    @ApiOperation(value = "0515会员管理-查询所有标签", notes = "会员管理-查询所有标签")
    @GetMapping({"/listTagMember"})
    public Result<?> listTagMember(@RequestParam(name = "tagId", defaultValue = "") String tagId, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) this.redisUtils.get("StoreId-" + token);
        if (oConvertUtils.isEmpty(storeId))
            return Result.error("请先到首页选择店铺");
        if (storeId.contains("过期"))
            return Result.error("店铺已过期，续费后才可操作");
        Tag tag = this.tagService.getById(tagId);
        List<MemberTag> list = this.memberTagService.list((Wrapper) ((QueryWrapper) (new QueryWrapper()).eq("store_id", storeId)).eq("tag_id", tagId));
        List<MemberManagement> mList = new ArrayList<>();
        for (MemberTag ele : list) {
            MemberManagement member = this.memberManagementService.getById(ele.getMemberId());
            mList.add(member);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("tag", tag);
        result.put("member", mList);
        return Result.ok(result);
    }

    @AutoLog("会员管理-删除标签")
    @ApiOperation(value = "0515会员管理-删除标签", notes = "会员管理-删除标签")
    @GetMapping({"/deleteTag"})
    public Result<?> deleteTag(@RequestParam(name = "tagId", defaultValue = "") String tagId, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) this.redisUtils.get("StoreId-" + token);
        if (oConvertUtils.isEmpty(storeId))
            return Result.error("请先到首页选择店铺");
        if (storeId.contains("过期"))
            return Result.error("店铺已过期，续费后才可操作");
        this.tagService.removeById(tagId);
        Map<String, Object> map = new HashMap<>();
        map.put("store_id", storeId);
        map.put("tag_id", tagId);
        this.memberTagService.removeByMap(map);
        return Result.OK();
    }

    @AutoLog("会员管理-新增标签 如果有员工，则把员工加入该标签")
    @ApiOperation(value = "0515会员管理-新增标签", notes = "会员管理-新增标签")
    @GetMapping({"/createTag"})
    public Result<?> createTag(@RequestParam(name = "tagName", required = true, defaultValue = "") String tagName, @RequestParam(name = "memberId", required = false, defaultValue = "") String memberId, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) this.redisUtils.get("StoreId-" + token);
        if (oConvertUtils.isEmpty(storeId))
            return Result.error("请先到首页选择店铺");
        if (storeId.contains("过期"))
            return Result.error("店铺已过期，续费后才可操作");
        if (StringUtils.isBlank(tagName))
            return Result.error("参数不足");
        Tag tag = new Tag();
        tag.setName(tagName);
        tag.setStoreId(storeId);
        this.tagService.save(tag);
        if (!StringUtils.isBlank(memberId)) {
            MemberTag memberTag = new MemberTag();
            memberTag.setMemberId(memberId);
            memberTag.setTagId(tag.getId());
            memberTag.setStoreId(storeId);
            this.memberTagService.save(memberTag);
        }
        return Result.OK(tag);
    }

    @AutoLog("会员管理-新增员工到标签")
    @ApiOperation(value = "0515会员管理-新增员工到标签", notes = "会员管理-新增员工到标签")
    @GetMapping({"/addMember2Tag"})
    public Result<?> addMember2Tag(@RequestParam(name = "tagId", required = true, defaultValue = "") String tagId, @RequestParam(name = "memberId", required = true, defaultValue = "") String memberId, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) this.redisUtils.get("StoreId-" + token);
        if (oConvertUtils.isEmpty(storeId))
            return Result.error("请先到首页选择店铺");
        if (storeId.contains("过期"))
            return Result.error("店铺已过期，续费后才可操作");
        if (StringUtils.isBlank(tagId) || StringUtils.isBlank(memberId))
            return Result.error("参数不足");
        MemberTag memberTag = new MemberTag();
        memberTag.setMemberId(memberId);
        memberTag.setTagId(tagId);
        memberTag.setStoreId(storeId);
        this.memberTagService.save(memberTag);
        return Result.OK();
    }
}

